package vip.ifmm.lehouse.commodity.service.listener;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;
import vip.ifmm.lehouse.commodity.service.dao.CommodityCommentDao;
import vip.ifmm.lehouse.commodity.service.event.StarToSqlEvent;
import vip.ifmm.lehouse.commodity.service.helper.ThreadHelper;
import vip.ifmm.lehouse.commodity.service.utils.RedisUtil;
import javax.annotation.Resource;


/**
 * 监听事件，为每个评论开启点赞数写回数据库任务
 *
 * @author Red
 * email: 1318944013@qq.com
 * date: 2019/6/21 14:41
 */
@Component
@Slf4j
public class StarToSqlEventListener implements ApplicationListener<StarToSqlEvent> {

    @Resource
    private CommodityCommentDao commentDao;

    @Resource
    private ThreadHelper threadHelper;

    @Value("${redis-star-key}")
    private  String REDIS_STAR_KEY;

    @Override
    public void onApplicationEvent(StarToSqlEvent event) {
        // 提交点赞数写回数据库定时任务
        threadHelper.schedule(() -> {
            // 获得评论ID
            int commodityId = event.getComment().getCommentId();
            // 写回数据库逻辑
            starWrite2Sql(commodityId);
        }, 10, 900);
    }

    // Redis中的点赞数 -> 数据库
    private void starWrite2Sql(int commentId) {
        // 获得Redis中的点赞数
        int starNum = RedisUtil.get(REDIS_STAR_KEY + commentId, Integer.class);
        // 点赞数大于0才写回数据库，减少写回次数
        if(starNum > 0) {
            commentDao.updateStar(commentId, starNum);
            log.info("点赞数写回数据库, id为: " + commentId);
        }
    }




}
